package com.thirdgroup.controller;

import com.alibaba.fastjson.JSONObject;
import com.wf.captcha.SpecCaptcha;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
生成图片验证码
1.导入easy-captcha依赖
2.使用easy-captcha技术封装的代码完成
 */
@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建验证码对象：宽高，有4个数字，字体
        SpecCaptcha specCaptcha = new SpecCaptcha(120,40,4);
        //获取验证码的值
        String verCode = specCaptcha.text().toLowerCase();
        System.out.println("verCode="+verCode);
        //把值存储session域中 as45
        HttpSession session = request.getSession();
        session.setAttribute("serverVerCode",verCode);
        //把验证码对象地址回写到页面中
        Map map = new HashMap();
        map.put("image",specCaptcha.toBase64());
        //转成JSON响应回login.html
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(map));
    }
}
